<template>
  <div class="index-card">
    <ConditionBox>
      <template #left>
        <div class="title">试用期考核评分规则</div>
      </template>
      <template #right>
        <a-button v-if="!props.review" @click="setRules">设置</a-button>
      </template>
    </ConditionBox>
    <a-divider />
    <a-table :data="rulesData" :pagination="false" stripe>
      <template #columns>
        <a-table-column title="考核节点" align="center">
          <template #cell="{ rowIndex }">
            <span v-if="rowIndex === 0">考核评价</span>
            <span v-if="rowIndex === 1">员工自评</span>
          </template>
        </a-table-column>
        <a-table-column title="考核总分" align="center">
          <template #cell="">
            {{ formData?.upperLimitScore ? formData?.upperLimitScore : '不限' }}
          </template>
        </a-table-column>
        <a-table-column title="评分计算方式" align="center">
          <template #cell="{}">
            <span v-if="formData?.scoreCalculation === 2"> 加权计算 </span>
            <span v-if="formData?.scoreCalculation === 1"> 加和计算 </span>
            <span v-if="!formData?.scoreCalculation">--</span>
          </template>
        </a-table-column>
        <a-table-column title="考核权重" align="center">
          <template #cell="{ rowIndex }">
            <span v-if="rowIndex === 0">
              {{ formData?.organizationEvaluation }} %
            </span>
            <span v-if="rowIndex === 1">
              <a-input-number
                v-if="!props.review"
                v-model="formData.selfEvaluation"
                style="width: 80px"
                @blur="weightChange"
                hide-button
              >
                <template #suffix> % </template>
              </a-input-number>
              <span v-else> {{ formData.selfEvaluation }} % </span>
            </span>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </div>
  <a-alert
    v-if="
      (!weightTotal || weightTotal !== 100) &&
      templateData.performanceAssessmentTemplateDimensionality?.length
    "
    type="error"
    >考核维度权重的和必须等于100.</a-alert
  >
  <div class="index-card">
    <ConditionBox>
      <template #left>
        <div class="title">考核维度</div>
      </template>
      <template #right></template>
    </ConditionBox>
    <a-divider />
    <a-table
      :columns="columns"
      :data="formData.performanceAssessmentTemplateDimensionality"
      :pagination="false"
    >
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #type="{ record }">
        {{ getNameByType(record.type) }}
      </template>
      <template #name="{ rowIndex }">
        <a-input
          style="width: 200px"
          v-model="
            formData.performanceAssessmentTemplateDimensionality[rowIndex].name
          "
        />
      </template>
      <template #weight="{ record, rowIndex }">
        <span v-if="![5, 6].includes(record.type)">
          <a-input-number
            v-if="!props.review"
            v-model="
              formData.performanceAssessmentTemplateDimensionality[rowIndex]
                .weight
            "
            style="width: 80px"
            hide-button
          >
            <template #suffix> % </template>
          </a-input-number>
          <span v-else>
            {{
              formData.performanceAssessmentTemplateDimensionality[rowIndex]
                .weight
            }}%
          </span>
        </span>
        <span v-else> 无 </span>
      </template>
      <template #optional="{ rowIndex }">
        <a-tooltip content="删除" position="left">
          <a-popconfirm content="是否确认删除该条数据?" @ok="del(rowIndex)">
            <icon-font
              type="icon-delete"
              :size="26"
              :style="{
                cursor: 'pointer',
                marginRight: '10px'
              }"
            />
          </a-popconfirm>
        </a-tooltip>
      </template>
    </a-table>
    <a-button v-if="!props.review" type="text" @click="add"
      >新增考核维度</a-button
    >
  </div>
  <ToolsDrawer
    v-model:visible="drawerVisible"
    @submit="submit"
    :data="currData"
    :selectedIndex="selectedIndex"
  />
  <RulesDrawer
    v-model:visible="rulesVisible"
    v-model:data="formData"
    @change="changeRules"
  />
</template>

<script setup lang="ts">
import { cloneDeep } from 'lodash';
import { PerformanceAssessmentTemplateDimensionality } from '@/apis/management/performance/baseSetting/template/type';
import ToolsDrawer from './ToolsDrawer.vue';
import RulesDrawer from '@/views/Management/Performance/PerformanceManagement/Probation/Components/AssessmentPlan/conponents/Tool/RulesDrawer.vue';
import { useVModel } from '@vueuse/core';
import { getProbationToolName } from '@/utils/probation';

const props = withDefaults(
  defineProps<{
    templateData: any;
    data?: PerformanceAssessmentTemplateDimensionality[];
    review?: boolean;
  }>(),
  {}
);
const emit = defineEmits([
  'update:visible',
  'handleOk',
  'update:data',
  'update:templateData'
]);

const formData = useVModel(props, 'templateData', emit);
const handleOk = () => {
  emit('handleOk');
};

const columns = ref<any>([
  {
    title: '序号',
    dataIndex: '',
    slotName: 'index'
  },
  {
    title: '考核维度名称',
    dataIndex: 'name',
    slotName: 'name'
  },
  {
    title: '考核工具',
    dataIndex: 'type',
    slotName: 'type'
  },
  {
    title: '配分/权重',
    dataIndex: 'weight',
    slotName: 'weight'
  }
]);
onMounted(() => {
  if (!props.review) {
    columns.value.push({
      title: '操作',
      dataIndex: 'optional',
      slotName: 'optional',
      width: 120
    });
  }
});
const currData = ref<PerformanceAssessmentTemplateDimensionality>({});
const drawerVisible = ref(false);
const add = () => {
  editIndex.value = -1;
  currData.value = {};
  drawerVisible.value = true;
};

const selectedIndex = computed(() => {
  const { performanceAssessmentTemplateDimensionality: dimension } =
    formData.value;
  if (!dimension || !dimension.length) return [];
  return dimension.map((object) => Number(object.type)); //设置已选择的指标
});
// 选择维度
const submit = (toolIndex: number[]) => {
  const tempIndex = toolIndex.filter((item) => item !== 5 && item !== 6); //去除没有权重的维度
  const remainder = 100 % tempIndex.length; //取模
  const weight = Math.floor(100 / tempIndex.length); //商
  let isAddRemainder = false; //余数是否已经新增过
  // 新增已选择
  if (toolIndex.length) {
    toolIndex.forEach((type) => {
      if (!selectedIndex.value.includes(type)) {
        let name = getProbationToolName(type, 1);
        let toolObj = { type, weight: 0, name };
        if (type !== 5 && type !== 6) {
          toolObj.weight = weight;
          if (!isAddRemainder) {
            toolObj.weight += remainder;
            isAddRemainder = true;
          }
        }
        formData.value.performanceAssessmentTemplateDimensionality.push(
          toolObj
        );
      } else {
        const delIndex =
          formData.value.performanceAssessmentTemplateDimensionality.findIndex(
            (item) => item.type === type
          );
        if (type !== 5 && type !== 6) {
          formData.value.performanceAssessmentTemplateDimensionality[
            delIndex
          ].weight = weight;
          if (!isAddRemainder) {
            formData.value.performanceAssessmentTemplateDimensionality[
              delIndex
            ].weight += remainder;
            isAddRemainder = true;
          }
        }
      }
    });
  }
  // 删除未选择
  selectedIndex.value.forEach((type) => {
    if (!toolIndex.includes(type)) {
      const delIndex =
        formData.value.performanceAssessmentTemplateDimensionality.findIndex(
          (item) => item.type === type
        );
      formData.value.performanceAssessmentTemplateDimensionality.splice(
        delIndex,
        1
      );
    }
  });
};
const del = async (index: number) => {
  formData.value.performanceAssessmentTemplateDimensionality.splice(index, 1);
};
const editIndex = ref(-1); //编辑项的下标，用以判断新增和编辑，下标小于0是新增数据。大于等于0则是修改此下标的值
const goEdit = (
  data: PerformanceAssessmentTemplateDimensionality,
  index: number
) => {
  editIndex.value = index;
  currData.value = data;
  drawerVisible.value = true;
};
const getNameByType = (type?: number) => {
  switch (type) {
    case 1:
      return '关键业绩考核';
    case 2:
      return '能力素质考核';
    case 3:
      return '工作计划考核';
    case 4:
      return '目标与关键成果法';
    case 5:
      return '加减分项';
    case 6:
      return '否决指标法';
    default:
      return '';
  }
};
const weightChange = () => {
  if (!formData.value) return;
  if (!formData.value.selfEvaluation) {
    formData.value.organizationEvaluation = 0;
  }
  if (!formData.value.selfEvaluation) formData.value.selfEvaluation = 0;
  formData.value.organizationEvaluation = 100 - formData.value.selfEvaluation;
};
const changeRules = (data: any) => {
  const { upperLimitType, scoreCalculation, upperLimitScore } = data;
  formData.value.upperLimitType = upperLimitType;
  formData.value.scoreCalculation = scoreCalculation;
  formData.value.upperLimitScore = upperLimitScore;
};
const rulesData = [{}, {}];
const rulesVisible = ref(false);
const setRules = () => {
  rulesVisible.value = true;
};
const weightTotal = computed(() => {
  return formData.value.performanceAssessmentTemplateDimensionality?.reduce(
    (accumulator, currentValue) => {
      const weight = currentValue?.weight ? currentValue?.weight : 0;
      return accumulator + weight;
    },
    0
  );
});
</script>

<style lang="less" scoped>
.index-card {
  border-radius: 4px;
  width: 800px;
  margin: 20px auto;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  padding: 20px;
  .title {
    font-weight: 600;
    font-size: 18px;
  }
}
</style>
